<?php
function upload($file,$thumb=false,$width=196,$height=163)
{
	$types = array('jpg', 'gif', 'png', 'bmp');
	$upload_Ymd = $name = date("Ymd");
	$uploaddir = 'images/'.$upload_Ymd.'/';
	$name = date("YmdHis");
	$num = rand(0,1000);
	$filename = $file['name'];
	$type_arr = explode('.',$filename);
	$count = count($type_arr);
	$type = $type_arr[$count - 1];

	$pinfo=pathinfo($file['name']);
	$ftype=strtolower($pinfo['extension']);
	if(!in_array($ftype, $types)) die('文件类型错误！');
	$uploadfile = $uploaddir . $name.$num.'.'.$ftype;
	$thumburl = $uploaddir . $name.$num.'_s.'.$ftype;

	if (!file_exists($uploaddir)) {
		mkdir($uploaddir,0777);
	}
	if (move_uploaded_file($file['tmp_name'],$uploadfile)) {
		if($thumb) $this->makethumb($uploadfile, $thumburl, $width, $height);
		return $uploadfile;
	} else {
		return '1111';
	}
}
		
function thumbnail($path){
  if($path == '') return '';
  $file = pathinfo($path);
  return $file['dirname'] .'/'. $file['filename'] .'_s.'. $file['extension'];
}

function makethumb($srcfile, $dstfile, $width, $height, $rate=100){ 
  $data = getimagesize($srcfile); 
  switch($data[2]){ 
	  case 1: $image = @imagecreatefromgif($srcfile); break; 
	  case 2: $image = @imagecreatefromjpeg($srcfile); break; 
	  case 3: $image = @imagecreatefrompng($srcfile); break; 
  } 
  if(!$image) return false; 
  $src_w = imagesx($image); $src_h = imagesy($image); 
  if($src_w * $height > $src_h * $width){
	  $src_x = $src_w; $src_y = 0;
	  $src_w = round($src_h * $width / $height); 
	  $src_x = ($src_x - $src_w) / 2;
  }else{
	  $src_x = 0; $src_y = $src_h;
	  $src_h = round($src_w * $height / $width);
	  $src_y = ($src_y - $src_h) / 2;
  } 
  $thumb = imagecreatetruecolor($width, $height);  
  imagecopyresized($thumb, $image, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
  imagejpeg($thumb, $dstfile, $rate); 
  
  imagedestroy($thumb);
  imagedestroy($image);
}
?>
